package org.nnxy.foodboot.config;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * JWT认证过滤器，拦截所有需要认证的请求
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Value("${jwt.header}")
    private String header;

    @Value("${jwt.token-prefix}")
    private String tokenPrefix;

    // 白名单路径列表
    private final List<String> whitelistPaths = Arrays.asList(
            "/api/user/login",
            "/api/user/register",
            "/swagger-ui/",
            "/v3/api-docs/",
            "/swagger-resources/"
    );

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        // 直接放行所有请求，不进行JWT验证
        filterChain.doFilter(request, response);
        
        /*
        // 以下是原来的验证逻辑，已被注释掉
        String requestURI = request.getRequestURI();
        
        // 白名单路径直接放行
        if (isWhitelistedPath(requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 获取token
        String token = request.getHeader("Authorization");
        
        if (token == null || !token.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\": 401, \"message\": \"未授权: 缺少有效Token\"}");
            return;
        }

        token = token.substring(7);  // 去掉"Bearer "前缀

        try {
            Claims claims = JwtUtils.parseToken(token, jwtSecret);
            if (claims.getExpiration().before(new Date())) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\": 401, \"message\": \"未授权: Token已过期\"}");
                return;
            }

            // 从JWT中提取用户信息，创建认证对象
            String username = claims.getSubject();
            Long userId = Long.parseLong(claims.get("userId").toString());

            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    username, null, Collections.emptyList());
            
            // 添加用户ID信息到认证详情中
            Map<String, Object> details = new HashMap<>();
            details.put("userId", userId);
            authentication.setDetails(details);

            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\": 401, \"message\": \"未授权: Token无效 - " + e.getMessage() + "\"}");
        }
        */
    }

    /**
     * 检查请求路径是否在白名单中
     */
    private boolean isWhitelistedPath(String requestURI) {
        return whitelistPaths.stream().anyMatch(requestURI::startsWith);
    }
} 